package ack.service;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.UUID;

@Service
public class AckPublisherServiceImpl {
  @Autowired
  private RabbitTemplate rabbitTemplate;


  public void sendMsg() {
    CorrelationData correlationData = new CorrelationData();
    String uuid = UUID.randomUUID()
            .toString();
    System.out.println("threadID:--" + Thread.currentThread()
            .getId());
    System.out.println("生产的id是：" + uuid);
    //如果你不设置id，发布确认回调的第一个参数还是有id是，broker生成的
    correlationData.setId(uuid);
    Object data = "msg:" + new Date();
    rabbitTemplate.convertAndSend("ackqueue", data, correlationData);
    //rabbitTemplate.waitForConfirms()
    //rabbitTemplate.waitForConfirmsOrDie();
    //回调确认是异步的，与发送数据的线程不是同一个
    rabbitTemplate.setConfirmCallback((cdata, ack, cause) -> {
      System.out.println("callback threadID:--" + Thread.currentThread()
              .getId());
      if (ack) {
        System.out.println(cdata.getId() + " 成功发送给broker");
      } else {
        System.out.println("消息发送失败---- 原因是：" + cause);
      }
    });
  }

  public void sendMsgReturnCallback() {
    CorrelationData correlationData = new CorrelationData();
    String uuid = UUID.randomUUID()
            .toString();
    correlationData.setId(uuid);

    rabbitTemplate.setReturnsCallback((returnedMessage) -> {
      System.out.println("returnedMessage.getReplyCode() = " + returnedMessage.getReplyCode());
      System.out.println("returnedMessage.getReplyText() = " + returnedMessage.getReplyText());
      System.out.println("returnedMessage.getRoutingKey() = " + returnedMessage.getRoutingKey());
      try {
        System.out.println("new String(returnedMessage.getMessage().getBody(),\"UTF-8\") = " + new String(returnedMessage.getMessage()
                .getBody(), "UTF-8"));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    });

    Object data = "return callback";
    //发给默认交换机或指定交换机，只要没有进入到队列，return回调都会执行
    //一定要记得在配置文件中进行配置
    rabbitTemplate.convertAndSend("asdf", data, correlationData);

  }


}
